import os,sys
from w1_ui import Ui_MainWindow
from PySide6.QtWidgets import QApplication,QMainWindow,QMessageBox
from PySide6.QtCore import Qt,Slot
from tableclass import TeacherExchange,TeacherList
import inc_db as db
import pathlib
import sqlite3
from loger import Logger
from TeacherManagementClass import dialogTeacherMutual,teacherManagement
from sessionManagementClass import sessionManagement
from initDBSQL import sql

root=pathlib.Path(__file__).parent
# db=sqlite3.connect(str(root/"exam.db"))
# cur = db.cursor()
log = Logger('exam',StreamLevel='debug',FileLevel='info').logger
class mywin(QMainWindow):
    def __init__(self,parent=None):
        super().__init__(parent)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.dialog=None
        self.activeExamID=db.getData("activeExamID")

        examRoomNum=21    #考场数
        examTeacherNum=2    #监考人数
        examNum=5   #考试科目数
        if self.activeExamID is None or int(self.activeExamID)==0: 
            self.initdb()
            db.setData("maxExamID",10)
            db.setData("activeExamID",0)
            self.maddexam()
            self.setWindowTitle(f"监考表")
        else:
            sql=f"select title,sessionNum,teacherNum,roomNum from exam_list where ID={self.activeExamID} ;"
            (s,r)=db.runsql(sql)
            r=r.fetchone()
            if(s and int(db.getData("activeExamID")) !=0 ):
                self.setWindowTitle(f"{r[0]} - 监考表")
                examRoomNum=r[3]    #考场数
                examTeacherNum=r[2]   #监考人数
                examNum=r[1]   #考试科目数

        self.table=TeacherExchange(examRoomNum=examRoomNum,examTeacherNum=examTeacherNum,examNum=examNum)
        self.ui.verticalLayout_3.addWidget(self.table)


        self.table2=TeacherList(rows=60)
        # self.table2.forbidden_cells={(1,1),(1,2)}
        # self.table2.refreshBackground()
        
        self.ui.verticalLayout_2.addWidget(self.table2)


        self.table.setAcceptDrops(True)


        item=self.table.item(0,1)
        item.setText(f"七年级语文\n八年级语文\n九年级文\n2025-12-25\n07:30~10:00")
        # self.table.setItem(0,1,item)
        item.setTextAlignment(Qt.AlignCenter)
        
        self.ui.label.setText("1234")

        self.ui.initdb.triggered.connect(self.initdb)      
        self.ui.m_teacherManaagement.triggered.connect(self.teacherManagement)
        self.ui.m_fromdbinput.triggered.connect(self.mFromDBinput)
        self.ui.m_addSession.triggered.connect(self.maddexam)
        self.ui.m_teacherMutual.triggered.connect(self.openTeacherMutualDialog)
        self.table2.s1.connect(self.table.getAvailability)
    
    def openTeacherMutualDialog(self):
        dialog=dialogTeacherMutual()
        dialog.exec()
    def initdb(self):
        log.debug("initdb")
        # from initDBSQL import sql
        # f=True
        # for t in sql:
        #     (s,r)=db.runsql(t)
        #     f=f and s
        #     if(not s):
        #         QMessageBox.warning(self,"新建表失败",f"{str(r)}")
        # if (f):
        #     QMessageBox.information(self,"成功","数据库已新建")
        #  self.dialog=dialogAddTeacher(self)
        #  self.dialog.exec()
        try:
            with open(db.root/"main.sql", 'r', encoding='utf-8') as f:
                sql_content = f.read()  # 读取整个 SQL 文件
        except FileNotFoundError:
            print(f"错误：SQL 文件 '{db.root/"main.sql"}' 不存在")
            return
        except Exception as e:
            print(f"读取 SQL 文件失败：{e}")
            return
        print(sql_content)
        try:
            db.cur.executescript(sql_content)
            db.db.commit()
            print(f"SQL 文件 '{db.root/"main.sql"}' 执行成功")

        except db.Error as e:
            print(f"执行 SQL 失败：{e}")
            if db.db:
                db.db.rollback()  # 执行失败时回滚事务


    def teacherManagement(self):
        log.debug("teacherManagement")
        tmw=teacherManagement(self)
        tmw.show()
    def mFromDBinput(self):
        childWind=teacherManagement(self)
        childWind.show()
        childWind.inputFromDB()
    def maddexam(self):
        childWind=sessionManagement(self)
        childWind.show()



if __name__ =="__main__":
    app=QApplication()
    window=mywin()
    window.show()
    sys.exit(app.exec())